package com.authine.cloudpivot.ext.service.ipml;


import com.authine.cloudpivot.foundation.orm.api.dml.JPANativeQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SyncResidentServiceImpl {

    @Autowired
    JPANativeQuery jpaNativeQuery;

    public void syncResidentAge() {
        String querySql = "SELECT id,age,IDNumber FROM `iknn4_resident` where IDNumber is not null";
        List<Map<String,Object>> list = jpaNativeQuery.getList(querySql, null, null);
        for (Map<String,Object> map : list){
            String id = map.get("id").toString();
            BigDecimal age =(BigDecimal) map.get("age");
            String idNumber = map.get("IDNumber").toString();
            try {
                if (isValidChineseID(idNumber)){
                    String birthDateString = idNumber.substring(6, 14);
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    LocalDate birthDate = LocalDate.parse(birthDateString, formatter);
                    LocalDate currentDate = LocalDate.now();
                    int i = currentDate.getYear() - birthDate.getYear();
                    BigDecimal ageNum = BigDecimal.valueOf(i);
                    if (age!=ageNum){
                        String updateSql =String.format("update iknn4_resident set age = %s where id = '%s'",ageNum,id);
                        jpaNativeQuery.getList(updateSql,null,null);
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    /**
     * 校验身份证
     * @param id
     * @return
     */
    public static boolean isValidChineseID(String id) {
        String regex = "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2][0-9]|3[0-1])\\d{3}([0-9Xx])$";
        return id.matches(regex);
    }
}
